package com.weibo.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.weibo.domain.BasicInfo;
import com.weibo.hibernate.PersonInfo;
import com.weibo.util.StaticUtil;


public class HandleRegist extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		
		String userName = request.getParameter("userName");
		String userId = request.getParameter("userId");
		String userPwd = request.getParameter("userPwd");
		if(StaticUtil.ifUserExisted(userId, userName))
		{
			response.sendRedirect("RegistError.html");
			return ;
		}
		
		BasicInfo b=new BasicInfo();
		b.setUserId(userId);
		b.setUserName(userName);
		b.setUserPwd(userPwd);
		b.setLoginId(StaticUtil.generateString(15));
		saveInformation(b);
		
		response.sendRedirect("RegistSuccess.html");
		return ;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
		
	}
	private boolean saveInformation(BasicInfo b)
	{
		Session session = null;
		Configuration config=null;
		SessionFactory factory = null;
		Transaction tran=null;

		config = new Configuration().configure();
		factory = config.buildSessionFactory();
		session = factory.openSession();
		tran = session.beginTransaction();
		session.saveOrUpdate(b);
		tran.commit();
		return true;
	}
}
